import { me, logout } from "@/api/system/user";
import { ElMessage } from 'element-plus'
import router from '@/router/index.js'

const state = () => ({
    user: {}
})

const mutations = {
    SET_USER(state, user) {
        state.user = user
    },
    REMOVE_USER(state) {
        state.user = {}
    }
}

const actions = {
    async getMe({ commit }) {
        const res = await me()
        if (res && res.code === 200) {
            commit('SET_USER', res.data)
        } else {
            ElMessage.error('获取个人信息失败')
        }
    },
    logOut({ commit }) {
        logout()
        commit('REMOVE_USER')
        // 1. 删除登陆令牌
        sessionStorage.removeItem('authorization')
        // 2. 跳转登录页
        router.replace('/login')
        // 3. 提示退出成功
        ElMessage.success('退出登陆成功')
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}